package cn.itcast.mapreduce.db.write;

import cn.itcast.mapreduce.db.bean.GoodsBean;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.db.DBConfiguration;
import org.apache.hadoop.mapreduce.lib.db.DBOutputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;


public class WriteDBDriver {

    public static void main(String[] args) throws Exception {
        //配置文件对象
        Configuration conf = new Configuration();

        //todo 配置当前作业需要使用的JDBC信息
        DBConfiguration.configureDB(
                conf, "com.mysql.jdbc.Driver",
                "jdbc:mysql://localhost:3306/mr?useUnicode=true&characterEncoding=utf8",
                "root",
                "root"
        );

        //创建作业的job类实例
        Job job = Job.getInstance(conf, WriteDBDriver.class.getSimpleName());

        //设置本次mr程序的驱动类
        job.setJarByClass(WriteDBDriver.class);

        //设置mapper类
        job.setMapperClass(WriteDBMapper.class);
        job.setMapOutputKeyClass(NullWritable.class);
        job.setMapOutputValueClass(GoodsBean.class);

        //设置reducer相关信息
        job.setReducerClass(WriteDBReducer.class);
        job.setOutputKeyClass(GoodsBean.class);
        job.setOutputValueClass(NullWritable.class);

        //设置当前作业的输入文件路径
        FileInputFormat.setInputPaths(job,new Path("C://mysqlout"));


        //设置程序的输入类
        job.setOutputFormatClass(DBOutputFormat.class);

        //todo 配置当前作业写入数据库的表，字段
        DBOutputFormat.setOutput(
                job,
                "itheima_goods_mr_write",
                "goodsId","goodsSn","goodsName","marketPrice","shopPrice","saleNum"
        );

        boolean b = job.waitForCompletion(true);
        System.exit(b ? 0 : 1);
    }

}
